import { asyncRoutes, constantRoutes } from '@/router'
import store from "@/store";
/**
 * 使用meta.role判断当前用户的角色是否有权限访问该路由
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    //当route不存在meta,或者没有roles说明是静态路由，不用权限校验
    return false
  }
}

/**
 * 通过递归过滤得到异步路由表。(存在嵌套路由所以使用递归找到所有的路由，并且进行权限校验)
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  //完整的路由列表
  routes: []
}

const mutations = {
  //进行路由拼接（将静态路由与异步路由拼接）得到完整的路由列表
  SET_ROUTES: (state, routes) => {
    if(store.getters.roles.includes('admin'))
   state.routes=routes
    else{
      state.routes=constantRoutes.concat(routes)
    }

  }
}

const actions = {
  //构造动态路由表
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes=filterAsyncRoutes(asyncRoutes, roles)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
